package com.ipan.builder.db.comment;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import com.ipan.builder.db.DatabaseOp;
import com.ipan.builder.entity.JpaColumnCfg;
import com.ipan.builder.entity.JpaEntityCfg;

/**
 * Oracle更新数据库注释实现
 * 
 * @author iPan
 * @version 2013-12-7
 */
public class OracleCommentOp extends BaseCommentOp {
	
	private static final String UPDATE_TABLE_SQL = "comment on table {table} is '{comment}'";
	private static final String UPDATE_COLUMN_SQL = "comment on column {table}.{column} is '{comment}'";

	public OracleCommentOp(DatabaseOp databaseOp) {
		super(databaseOp);
	}

	public void updateTableComment(JpaEntityCfg entityCfg) {
		String tableName = entityCfg.getTableName();
		String tableComment = entityCfg.getTableComment();
		String sql = null;
		sql = this.fillSql(UPDATE_TABLE_SQL, SQL_TABLE, tableName);
		sql = this.fillSql(sql, SQL_COMMENT, tableComment);
		databaseOp.execute(sql, null);
	}

	public void updateColumnComment(JpaEntityCfg entityCfg) {
		String tableName = entityCfg.getTableName();
		List<JpaColumnCfg> columnList = entityCfg.getAllColumnCfg();
		String baseSql = this.fillSql(UPDATE_COLUMN_SQL, SQL_TABLE, tableName);
		String sql = null;
		Connection conn = null;
		Statement statement = null;
		try {
			conn = databaseOp.getConnection();
			for (JpaColumnCfg columnCfg : columnList) {
				if (columnCfg.isTransient() || columnCfg.isAssociateColumn()) { // 排除Transient以及关联字段
					continue;
				}
				String field = columnCfg.getName();
				String comment = columnCfg.getComment();
				sql = this.fillSql(baseSql, SQL_COLUMN, field);
				sql = this.fillSql(sql, SQL_COMMENT, comment);
				statement = conn.createStatement();
				log.info(sql);
				statement.execute(sql);
			}
		} catch (SQLException e) {
			databaseOp.throwJDBCException(e, sql, null);
		} finally {
			databaseOp.closeStatement(statement);
			databaseOp.closeConnection(conn);
		}
	}
	
}
